<!-- AirFreightContent.vue -->
<template>
  <div class="air-freight-content">
    <BaseFreightTable
        :headers="headers"
        :tableData="currentAirBusiness"
        @update:tableData="updateAirBusiness"
        :matchingLocationsHeaders="matchingLocationsHeaders"
        :matchingLocationsData="matchingLocationsData"
        :feeHeaders="feeHeaders"
        :feeData="safeFeeData"
        @update:feeData="updateFeeTable"
        :businessType="businessType"
        :calculators="safeFeeData"
        :defaultCalculator="defaultCalculator"
        @calculator-selected="onCalculatorSelected"
        @calculator-data-change="onCalculatorDataChange"
        @row-focus="handleRowFocus"
    />
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import BaseFreightTable from './BaseFreightTable.vue'
import { commonFeeHeaders, getCommonHeader, getCalculatorData } from './sharedFreightData.js'
import { debounce } from 'lodash';
import { createNewBusiness, createNewFeeRecord } from './createBusinessRecords.js'

export default {
  name: 'AirFreightContent',
  components: {
    BaseFreightTable
  },
  props: {
    freightForwarderData: {
      type: Object,
      required: true,
      default: () => ({
        business: []
      })
    },
    businessId: {
      type: String,
      required: true
    }
  },
  setup(props, { emit }) {
    const businessType = ref('air');
    const currentBusinessId = ref(props.businessId);

    const headers = [
      { field: 'id', ...getCommonHeader('id'), visible: false },
      { field: 'startPort', ...getCommonHeader('startPort') },
      { field: 'endPort', ...getCommonHeader('endPort') },
      { field: 'triangleTrade', ...getCommonHeader('triangleTrade') },
      { field: 'transitPort', ...getCommonHeader('transitPort') },
      { field: 'transportMode', ...getCommonHeader('transportMode') },
      { field: 'currency', ...getCommonHeader('currency') },
      { field: 'carrier', ...getCommonHeader('carrier') },
      { field: 'carrierCode', ...getCommonHeader('carrierCode') },
      { field: 'uld', text: 'ULD', cellType: 'cellText' },
      { field: 'containerGrade', ...getCommonHeader('containerGrade') },
      { field: 'serviceLiver', ...getCommonHeader('serviceLiver') },
      { field: 'carrierLevel', ...getCommonHeader('carrierLevel') },
      { field: 'product', ...getCommonHeader('product') },
      { field: 'commLocal', ...getCommonHeader('commLocal') },
      { field: 'controlCustomer', ...getCommonHeader('controlCustomer') },
      { field: 'shipper', ...getCommonHeader('shipper') },
      { field: 'consignee', ...getCommonHeader('consignee') },
      { field: 'unit', ...getCommonHeader('unit') },
      { field: 'transportTime', ...getCommonHeader('transportTime') },
      { field: 'frequency', ...getCommonHeader('frequency') },
      { field: 'frequencyUnit', ...getCommonHeader('frequencyUnit') },
      { field: 'startDate', ...getCommonHeader('startDate') },
      { field: 'expiryDate', ...getCommonHeader('expiryDate') },
      { field: 'customerContractNo', ...getCommonHeader('customerContractNo') },
      { field: 'contractLink', ...getCommonHeader('contractLink') },
      { field: 'contractNo', ...getCommonHeader('contractNo') },
      { field: 'publish', ...getCommonHeader('publish') }
    ]

    const feeHeaders = commonFeeHeaders
    const matchingLocationsHeaders = ['Field', 'Location']
    const matchingLocationsData = [
      { field: 'Field 1', location: 'Location 1' },
      { field: 'Field 2', location: 'Location 2' },
    ]
    const calculators = getCalculatorData()

    const defaultCalculator = ref({
      code: 'UNT',
      name: '单位计算器'
    })

    const createCalculatorData = (type) => {
      switch (type) {
        case 'UNT':
          return {
            unitPrice: 0,
            agentRate: false,
            unitPriceValue: 0
          }
          // 在这里添加其他计算器类型的初始数据结构
        default:
          return {}
      }
    }


    const updateCalculatorData = (calculatorData, feeIndex) => {
      const currentBusiness = currentAirBusiness.value[0];
      if (currentBusiness && currentBusiness.feeTable && currentBusiness.feeTable[feeIndex]) {
        currentBusiness.feeTable[feeIndex].calculator = {
          ...calculatorData,
          parentId: currentBusiness.id, // 添加主表 id
          feeId: currentBusiness.feeTable[feeIndex].id // 添加费用表项 id
        };
        updateAirBusiness(currentBusiness);
      }
    };

    const onCalculatorSelected = (calculator, feeIndex) => {
      console.log('Calculator selected:', calculator, 'for fee index:', feeIndex);
      const currentBusiness = currentAirBusiness.value[0];
      if (currentBusiness && currentBusiness.feeTable && currentBusiness.feeTable[feeIndex]) {
        const calculatorData = {
          type: calculator.code,
          data: createCalculatorData(calculator.code),
          parentId: currentBusiness.id,
          feeId: currentBusiness.feeTable[feeIndex].id
        };
        updateCalculatorData(calculatorData, feeIndex);
      }
    }
    const safeCalculators = computed(() => {
      const currentBusiness = currentAirBusiness.value[0] || {};
      return Array.isArray(currentBusiness.feeTable)
          ? currentBusiness.feeTable.map(fee => {
            if (fee.calculator && fee.calculator.type) {
              return {
                type: fee.calculator.type,
                data: fee.calculator.data || createCalculatorData(fee.calculator.type)
              };
            } else {
              return createDefaultCalculator();
            }
          })
          : [createDefaultCalculator()];
    });

    const createDefaultCalculator = () => ({
      type: defaultCalculator.value.code,
      data: createCalculatorData(defaultCalculator.value.code)
    });

    const safeFeeData = computed(() => {
      if (!Array.isArray(currentAirBusiness.value) || currentAirBusiness.value.length === 0) {
        console.log('currentAirBusiness is not an array or is empty');
        return [];
      }
      const currentBusiness = currentAirBusiness.value[0] || {};
      return Array.isArray(currentBusiness.feeTable) ? currentBusiness.feeTable : [];
    });

    const currentAirBusiness = computed(() => {
      console.log('computed currentAirBusiness:', props.freightForwarderData);
      if (!props.freightForwarderData || !Array.isArray(props.freightForwarderData[businessType.value])) {
        console.log('No data for businessType:', businessType.value);
        return [createNewBusiness(currentBusinessId.value,businessType)];
      }
      const businessData = props.freightForwarderData[businessType.value];
      console.log('Current business data:', businessData);
      return businessData.length > 0 ? businessData : [createNewBusiness(currentBusinessId.value,businessType)];
    });

    const isRowEmpty = (row) => {
      if (!row) return true;
      const fieldsToIgnore = ['id', 'parentId'];
      return Object.entries(row).every(([key, value]) => {
        if (fieldsToIgnore.includes(key)) return true;
        return value === '' || value === null || value === undefined ||
            (typeof value === 'object' && Object.keys(value).length === 0);
      });
    };

    const updateAirBusiness = debounce((updatedRow) => {
      console.log('Updating air business:', updatedRow);
      if (!updatedRow || !updatedRow.businessType) {
        console.error('Invalid updatedRow or missing businessType:', updatedRow);
        return;
      }
      console.log('Updated air business data:', JSON.parse(JSON.stringify(updatedRow)));
      emit('update:freightForwarderData', [updatedRow]);
    }, 300);

    const updateFeeTable = (newFeeData) => {
      console.log('Updating fee table:', newFeeData);
      const airBusiness = currentAirBusiness.value[0];
      if (airBusiness && airBusiness.id === newFeeData.parentId) {
        const nonEmptyRows = newFeeData.filter(row => !isRowEmpty(row));
        const emptyRow = newFeeData.find(isRowEmpty) || createNewFeeRecord(airBusiness.id);
        airBusiness.feeTable = [...nonEmptyRows, emptyRow];
        updateAirBusiness(airBusiness);
      } else {
        console.warn('Received fee data for a different business record');
      }
    };
    const onCalculatorDataChange = (data) => {
      console.log('Calculator data changed:', data);
      // 在这里处理计算器数据变化
    };


    const onUnitPriceChange = (unitPrice, feeIndex) => {
      console.log('Unit price changed:', unitPrice, 'for fee index:', feeIndex);
      const currentBusiness = currentAirBusiness.value[0];
      if (currentBusiness && currentBusiness.feeTable && currentBusiness.feeTable[feeIndex]) {
        currentBusiness.feeTable[feeIndex].calculator.unitPriceValue = parseFloat(unitPrice);
        updateAirBusiness(currentBusiness);
      }
    }

    const onAgentRateChange = (agentRate) => {
      console.log('Agent rate changed:', agentRate)
    }

    const handleRowFocus = (row) => {
      console.log('Row focus changed. New currentBusinessId:', row.id);
      currentBusinessId.value = row.id;
    };

    watch(() => props.freightForwarderData, (newValue) => {
      console.log('AirFreightContent received new freightForwarderData:', newValue);
      if (newValue && newValue.air) {
        console.log('Updating air data');
        // 如果需要，这里可以添加额外的更新逻辑
      }
    }, { deep: true });

    return {
      headers,
      currentAirBusiness,
      matchingLocationsHeaders,
      matchingLocationsData,
      feeHeaders,
      calculators,
      updateAirBusiness,
      updateFeeTable,
      onCalculatorSelected,
      onUnitPriceChange,
      onAgentRateChange,
      handleRowFocus,
      safeFeeData,

      defaultCalculator,
      onCalculatorDataChange,

      safeCalculators,
      businessType
    }
  }
}
</script>
